package cn.rumoss.nettytest.time;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer{
  
  private int port;
  
  public TimeServer(int port) {
    this.port = port;
  }
  
  public void run() throws Exception {
    
    // 处理I/O操作的多线程事件循环器
    EventLoopGroup bossGroup = new NioEventLoopGroup();// acceptor 用来接收进来的连接
    EventLoopGroup workerGroup = new NioEventLoopGroup();// client 处理已经被接收的连接
    
    try{
      // 启动NIO服务的辅助启动类
      ServerBootstrap boot = new ServerBootstrap();
      boot.group(bossGroup,workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<SocketChannel>(){// 处理一个最近的已经接收的Channel
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline()// 当你的程序变的复杂时,可能你会增加更多的处理类到pipline上,
              .addLast(new TimeServerHandler());// 然后提取这些匿名类到最顶层的类上
            }
        })
        // 设置这里指定的通道实现的配置参数
        .option(ChannelOption.SO_BACKLOG,128)// 用来接收进来的连接
        .childOption(ChannelOption.SO_KEEPALIVE,true);// 发送出去的连接
      
      // 绑定端口,开始接收到来的数据
      ChannelFuture f = boot.bind(port).sync();
      // 等到Server Socket关闭,关闭Server
      f.channel().closeFuture().sync();
      
    }finally{
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
    
  }
  
  public static void main(String[] args) throws Exception {
    
    int port;
    if(args.length>0) {
      port = Integer.parseInt(args[0]);
    }else {
      port = 8080;
    }
    new TimeServer(port).run();
    
  }
  
}
